var EXPORTED_SYMBOLS = ['LOG', 'GSYNC_UTILS', 'Bookmark'];

const Cc = Components.classes;
const Ci = Components.interfaces;

const LOG = {

    LEVEL_TRACE: "TRACE",
    LEVEL_DEBUG: "DEBUG",
    LEVEL_INFO: "INFO",
    LEVEL_WARN: "WARN",
    LEVEL_ERROR: "ERROR",
    LEVEL_FATAL: "FATAL",
    
    consoleService: Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService),
    
    browserWindow: Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator).getMostRecentWindow("navigator:browser"),
    
    log: function(level, message){
    
        var patteredMessage = "[" + level + "] " + message;
        if (this.browserWindow) {
            this.browserWindow.dump(patteredMessage + "\n");
        }
        this.consoleService.logStringMessage(patteredMessage);
    },
    
    trace: function(message){
    
        //this.log(this.LEVEL_TRACE, message);
    },
    
    debug: function(message){
    
        this.log(this.LEVEL_DEBUG, message);
    },
    
    info: function(message){
    
        this.log(this.LEVEL_INFO, message);
    },
    
    warn: function(message){
    
        this.log(this.LEVEL_WARN, message);
    },
    
    error: function(message, exception){
    
        this.log(this.LEVEL_ERROR, message);
    },
    
    fatal: function(message, exception){
    
        this.log(this.LEVEL_FATAL, message);
    },
    
    inspect: function(object){
    
        for (property in object) {
            dump(property);
        }
    }
};

function myLogToConsole(aMessage, aSourceName, aSourceLine, aLineNumber, aColumnNumber, aFlags, aCategory){

    var consoleService = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
    var scriptError = Cc["@mozilla.org/scripterror;1"].createInstance(Ci.nsIScriptError);
    scriptError.init(aMessage, aSourceName, aSourceLine, aLineNumber, aColumnNumber, aFlags, aCategory);
    consoleService.logMessage(scriptError);
}



var GSYNC_UTILS = {

    openInNewTab: function(url, focus){
    
        dump("openInNewTab()\n");
        
        var windowManger = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
        
        dump(windowManger + "\n");
        var topWindow = windowManager.getMostRecentWindow('navigator:browser');
        dump(topWindow + "\n");
        if (topWindow) {
        
            var content = topWindow.document.getElementById('content');
            content.selectedTab = content.addTab(url);
            if (focus) {
                topWindow.focus();
            }
        }
    },
    
    getBrowserWindow: function(){
    
        var wm = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
        return wm.getMostRecentWindow("navigator:browser");
    },
    
    
    closeBrowser: function(){
    
        const nsIAppStartup = Ci.nsIAppStartup;
        // Notify all windows that an application quit has been requested.
        var observerService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
        var cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool);
        observerService.notifyObservers(cancelQuit, "quit-application-requested", null);
        // Something aborted the quit process. 
        if (cancelQuit.data) {
            return;
        }
        // Notify all windows that an application quit has been granted.
        observerService.notifyObservers(null, "quit-application-granted", null);
        // Enumerate all windows and call shutdown handlers
        var windowManager = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
        var windows = wm.getEnumerator(null);
        while (windows.hasMoreElements()) {
            var window = windows.getNext();
            if (("tryToClose" in window) && !window.tryToClose()) {
                return;
            }
        }
        var startupService = Cc["@mozilla.org/toolkit/app-startup;1"].getService(nsIAppStartup)
        startupService.quit(nsIAppStartup.eAttemptQuit);
    },
    
    doInRequest: function(requestUrl, queryString, requestMethod, ajax, callback, context){
    
        var request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
        request.open(requestMethod, requestUrl, ajax);
        if (requestMethod == "POST") {
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        LOG.debug("GSYNC_UTILS#doInRequest() Contacting url:" + requestUrl + " query:" + queryString + " method:" + requestMethod + " ajax:" + ajax);
        request.send(queryString);
        
        var response = request.responseText;
        LOG.trace("GSYNC_UTILS#doInRequest() status:" + request.status + " response:" + request.responseText);
        if (request.status == 200) {
            if (request.responseText.indexOf("ServiceLoginAuth?service=bookmarks") > 0) {
                LOG.error("GSYNC_UTILS#doInRequest() Failed to contact '" + requestUrl + ". Not authorized!");
                LOG.debug("GSYNC_UTILS#doInRequest() status:" + request.status + " response:" + request.responseText);
            } else {
                return callback.call(context, request);
            }
        } else {
            //TODO throw error
            LOG.error("GSYNC_UTILS#doInRequest() Failed to contact '" + requestUrl + "'. Response code is " + request.status);
            return;
        }
    },
}

function Bookmark(){

    this.title = "";
    this.link = "";
    this.date = "";
    this.id = "";
    this.description = "";
    this.label = "";
}

Bookmark.prototype.toString = function(){

    return "Bookmark(id='" + this.id + "',title='" + this.title + "',link='" + this.link + "'label='" + this.label + "')";
}
